﻿using System;
using System.Text;
using System.Xml.Linq;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using SPQueryToSql.Extensions;

namespace SPQueryToSql.ApplicationObjects.CAML
{
    internal class Value
    {
        public string Type;
        public string Text;

        public Value(XElement element)
        {
            Type = element.AttributeValueString("Type", string.Empty);
            if(element.Element(SPQueryToSql.CAML.Today)!=null)
            {
                Text = SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Today);
            }
            else if (element.Element(SPQueryToSql.CAML.Now) != null)
            {
                Text = SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Now);
            }
            else if (element.Element(SPQueryToSql.CAML.UserID) != null)
            {
                Text = SPContext.Current.Web.CurrentUser.ID.ToString();
            }
            else
            {
                Text = element.Value;
            }
        }

        public override string ToString()
        {
            return ToString(0);
        }

        public string ToString(int tabQnt)
        {
            var sb = new StringBuilder();
            const string tab = @"    ";
            for (var i = 0; i < tabQnt; i++) sb.Append(tab);
            sb.Append("<Value");
            if (!string.IsNullOrEmpty(Type))
                sb.AppendFormat(@" Type=""{0}"">", Type);
            else
                sb.Append(">");
            sb.Append(Text);
            sb.Append("</Value>");
            sb.Append(Environment.NewLine);
            return sb.ToString();
        }
    }
}
